<template>
  <div class="createPost-container">
    <el-form class="form-container" :model="postForm" :label-position="labelPosition" :rules="rules" ref="postForm" action="/tools/oss/uploadVideo">
      <div class="createPost-main-container">
        <el-col :span="12" :offset="6">
          <el-form-item label="课程标签" prop="tag">
            <el-input v-model="postForm.tag" placeholder="请输入课程标签"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="lessonType" >
            <el-radio-group v-model="postForm.lessonType" :disabled="this.isModify">
              <el-radio
              v-for="item in options"
              :key="item.code"
              :label="item.code">{{ item.msg }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="录播-直播" prop="isVideo" >
            <el-radio-group v-model="postForm.isVideo" >
              <el-radio :label='0'>录播课</el-radio>
              <!-- <el-radio :label='1'>直播课</el-radio> -->
            </el-radio-group>
          </el-form-item>
          <el-form-item label="课程类型" prop="isFree">
            <el-radio-group v-model="postForm.isFree">
              <el-radio :label='true'>免费课</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上课日期" prop="scheduleTime">
            <el-date-picker
              v-model="postForm.scheduleTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              :editable="false"
              :clearable="false"
              style="width: 100%;"
              ></el-date-picker>
          </el-form-item>
          <el-form-item label="上课时间" required class='unlimtFormItem'>
            <el-col :span="5">
              <el-form-item prop="teachingStartTime">
                <el-time-picker 
                  format='HH:mm'
                  value-format='HH:mm'
                  placeholder="选择开始时间"
                  v-model="postForm.teachingStartTime"
                  :editable="false"
                  :clearable="false"
                  @change="vaildateTime"
                  style="width: 100%;">
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="1" style="text-align:center">--</el-col>
            <el-col :span="5">
              <el-form-item prop="teachingEndTime">
                <el-time-picker
                  format='HH:mm'
                  value-format='HH:mm'
                  placeholder="选择结束时间"
                  v-model="postForm.teachingEndTime"
                  :editable="false"
                  :clearable="false"
                  @change="vaildateTime"
                  style="width: 100%;">
                </el-time-picker>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="上课主题" prop="lessonTopic">
            <el-input v-model="postForm.lessonTopic" placeholder="请输入上课主题（最多30个字符）" maxlength=30 ></el-input>
          </el-form-item>
          <el-form-item label="授课老师" prop="teacherId">
            <el-select v-model="postForm.teacherId" placeholder="请选择授课老师" style="width: 100%;">
              <el-option v-for="(teacher,index) in teachers" :key='index' :label="teacher.teacherName" :value="teacher.id"></el-option>
            </el-select>
          </el-form-item>
          <template v-if="postForm.lessonType == 2">
            <el-form-item label="图文内容">
              <Tinymce :height='30' :value='postForm.content' ref="editor" v-model="postForm.content" />
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="视频信息">
            </el-form-item>
            <el-form-item label="课程状态">
              <el-col :span="20" class="readonlyInput">
                <el-input :placeholder="(!postForm.status ? '待上传' : '已上传')" v-model="getLessonStatus"  readonly></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="视频" prop="videoUrl">
              <el-input v-model="postForm.videoUrl" type='text' style='display:none'></el-input>
              <el-upload
                ref="upload"
                :headers="headers"
                action="/tools/oss/uploadVideo"
                :before-upload="onBeforeUpload"
                :on-success="handleUploadSuccess"
                :on-remove="handleRemove"
                :on-progress="handProgress"
                :file-list="fileList"
                :show-file-list="false"
                :auto-upload="true"
                :accept="'.mp4'"
                :limit="2">
                <el-button slot="trigger" size="small" type="primary" plain>上传视频</el-button>
                <el-button size="small" type="danger"  @click="clearUpload">移除</el-button>
              </el-upload>
              <video
                v-if='postForm.videoUrl' 
                ref="videoBox"
                id="testVideo" 
                class="video-js" 
                height="300px"
                preload="auto"
                controls="" 
                :src="postForm.videoUrl">
              </video>
              <el-progress :text-inside="true" :stroke-width="16" :percentage="uploadProgress" v-show='uploadProgress'></el-progress>
            </el-form-item>
          </template>
          <el-form-item class="leftPaddingChange">
            <el-button  type="primary" :disabled='preventSumit' v-loading='preventSumit' size="small" @click="submitForm('postForm')">保存</el-button>
            <el-button  size="small" @click="cancelChangeLesson" plain>取消</el-button>
          </el-form-item>
        </el-col>
      </div>
    </el-form>
  </div>
</template>

<script>

/*
  时间格式问题
   service response  时间戳---new Date().getTime
   service request   string--- '2018-08-09' '19:22'
   datePiker default string--- '2018-08-09' '19:22'
   form vailed       string--- '2018-08-09' '19:22'

*/
import { validateURL } from '@/utils/validate'
import { createLesson, modifyLesson, getLessonEnums } from '@/api/curriculum'
import { getTeacherList } from '@/api/teacher'
import { getToken } from '@/utils/auth' // 验权
import Tinymce from '@/components/Tinymce'
import moment from 'moment'
export default {
  name: 'add',
  props:{
    modifyData:{
      type:Object,
      required:false
    }
  },
  components: { Tinymce },
  data() {
    const validateRequire = (rule, value, callback) => {
      this.postForm[rule.field] = this.postForm[rule.field].trim()
      if (!value) {
        this.$message({
          message: this.i18n[rule.field] + '为必填项',
          type: 'error',
          duration: 1000
        })
        callback(new Error(this.i18n[rule.field] + '为必填项'))
      } else {
        callback()
      }
    }
    return {
      options:[],
      headers:{},
      teachers:[],
      fileList:[],
      statusText:['', '已上传'],
      labelPosition:'right', // 每一行 文字位置 element 配置
      isModify:false, // 新增 或者 修改
      preventSumit:false,
      uploadProgress:0,
      progressFactor:0.96,
      postForm:{
        tag:'', // 课程标签
        lessonType:1, // 0：录播 1：直播
        isVideo: 0,
        isFree:true, // 0：免费 1：收费
        scheduleTime:'', // 开课日期
        teachingStartTime:'', // 起始时间
        teachingEndTime:'', // 结束时间
        lessonTopic:'', // 课程主题
        teacherId:'', // 授课老师
        status:'', // 课程状态
        videoUrl:'' // 视频地址
        // videoInfo:'', // 视频信息
      },
      loading: false,
      i18n: {
        tag:'课程标签',
        lessonType:0,
        isFree:true,
        scheduleTime:'上课日期',
        teachingStartTime:'开始上课时间',
        teachingEndTime:'结束上课时间',
        lessonTopic:'上课主题',
        teacherId:'授课老师',
        // videoInfo:'视频信息',
        status:'课程状态',
        videoUrl:'上传视频'
      },
      rules: {
        tag: [
          { validator: validateRequire, trigger: 'blur' },
          { required: true, message: '请输入课程标签', trigger: 'blur' }
        // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        lessonType: [{ required: true, message: '请选录播-直播', trigger: 'change' }],
        isFree: [{ required: true, message: '请选课程类型', trigger: 'change' }],
        scheduleTime: [{ type: 'string', required: true, message: '请选择上课日期', trigger: 'change' }],
        teachingStartTime: [{ type: 'string', required: true, message: '请选择开始时间', trigger: 'change' }],
        teachingEndTime: [{ type: 'string', required: true, message: '请选择结束时间', trigger: 'change' }],
        lessonTopic:[
          { validator: validateRequire, trigger: 'blur' },
          { required: true, message: '请输入课程主题', validator: validateRequire, trigger: 'blur' },
          { min: 1, max: 30, message: '最多输入30个字符', trigger: 'blur' }
        ],
        teacherId: [{ required: true, message: '请至选择授课老师', trigger: 'change' }],
        videoUrl: [{ type: 'string', required: true, message: '请上传视频', trigger: 'change' }]
      }
    }
  },
  created() {
    // 是否是处于 修改状态
    this.isModify = !!this.modifyData
    //如果是 处于 修改状态 , 给 postForm 传值
    if(this.isModify){
      this.postForm = Object.assign({}, this.postForm, this.modifyData)
      this.postForm.videoUrl && (this.fileList = [{ url:this.postForm.videoUrl, name:this.postForm.videoUrl }])
      this.postForm.scheduleTime = this.formateDate(this.postForm.scheduleTime, 'YYYY-MM-DD')
      this.postForm.teachingStartTime = this.formateDate(this.postForm.teachingStartTime, 'HH:mm')
      this.postForm.teachingEndTime = this.formateDate(this.postForm.teachingEndTime, 'HH:mm')
    }

    // 获取 授课老师列表
    getTeacherList().then(response => {
      const { code, data, message } = response
      code == '0' && (this.teachers = this.teachers.concat(data)) || this.$message({ message, type:'error', duration:2000 })
    }
    )

    getLessonEnums().then(res => {
      const { data } = res
      this.options = data
    })
  },
  mounted() {
    // this.getSections();
    this.headers = { accessToken:getToken() }
  },
  methods: {
    lessonChange(targetFun, params, message) {
      targetFun(params).then(response => {
        const { code } = response
        if (code == 0) {
          this.$notify({
            title: '成功',
            message: message,
            type: 'success',
            duration: 1000
          })
          this.loading = false
          this.isModify && this.$emit('modifycomplete', true)
          this.$router.push('list')
        }
      }).catch(reject => {
        this.$emit('modifycomplete', false)
      })
    },
    modifyOrAddLesson() {
      const targetFun = this.isModify ? modifyLesson : createLesson
      this.postForm.tag = this.postForm.tag.trim()
      this.postForm.lessonTopic = this.postForm.lessonTopic.trim()
      const params = this.postForm
      const message = this.isModify ? '课程已保存' : '课程修改成功'
      this.lessonChange(targetFun, params, message)
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          // if(!this.vaildateTime()|| !this.vaildateVedio()){return false}
          if(!this.vaildateTime()){ return false }
          this.loading = true
          this.modifyOrAddLesson()
        } else {
          return false
        }
      })
    },
    clearUpload() {
      if (!this.fileList.length) return false
      this.$refs.upload.clearFiles()
      this.fileList = []
    },
    handleUploadSuccess(response, file, fileList) {
      const { code, data:{ picUrlList }, message } = response
      if(code == 0){
        this.fileList = [{ name:picUrlList[0], url:picUrlList[0] }]
        this.uploadProgress = 100
        this.preventSumit = false
        setTimeout(() => { this.uploadProgress = 0 }, 1000)
      }else{
        this.$refs.upload.clearFiles()
        this.$notify({
          title: '失败',
          message: message,
          type: 'error',
          duration: 3000
        })
        this.preventSumit = false
      }
    },
    handProgress(file) {
      this.uploadProgress = parseInt(file.percent * this.progressFactor)
    },
    onBeforeUpload(file){
      this.progressFactor = Math.random(1)
      this.preventSumit = true
      //
      // if(!file.type.includes('android')){
      //   this.$notify({
      //       title: '失败',
      //     message: '请上传apk文件',
      //     type: 'error',
      //     duration: 2000
      //   })
      //   return false;
      // }else{
      //   return true;
      // }
    },
    handleRemove(file) {
      this.$refs.upload.clearFiles()
      this.fileList = []
    },
    vaildateTime() {
      const start = this.postForm.teachingStartTime
      const end = this.postForm.teachingEndTime
      if(!start || !end){ return false }
      const status = (start < end)
      !status && this.$message({
        message: '开始时间不能超过结束时间',
        type: 'error',
        duration: 2000
      })
      return status
    },
    vaildateVedio() {
      !this.fileList.length && this.$message({
        message: '请上传视频',
        type: 'error',
        duration: 2000
      })
      return this.fileList.length > 0
    },
    cancelChangeLesson() {
      this.$refs.postForm.resetFields()
      this.isModify && this.$emit('modifycomplete', true)
      this.isModify || this.$router.push('list')
    },
    formateDate(timeOrDate, type) {
      // timeStamp -- 'stamp'
      let result = ''
      switch(type){
        case 'stamp':
          result = new Date(timeOrDate).getTime()
          break
        default:
          result = moment(timeOrDate).format(type)
      }
      return result
    }
  },
  computed:{
    getLessonStatus() {
      if(this.fileList.length > 0) {
        this.postForm.videoUrl = this.fileList[0].url
        this.postForm.status = 1
      }else{
        this.postForm.videoUrl = ''
        this.postForm.status = 0
      }
      return this.statusText[this.postForm.status]
    },
    // trimTag (){
    //   this.postForm.tag = this.postForm.tag.trim()
    //   this.$forceUpdate()
    // },
    trimTag: {
      get: function() {
        return this.postForm.tag
      },
      set: function() {
        this.postForm.tag = this.postForm.tag.trim()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import 'src/styles/mixin.scss';
$left-offset:96px;
.createPost-main-container{
  padding: 50px 0;
  @include clearfix;
}
.leftPaddingChange{
    button{
      min-width:100px;
    }
}
</style>
<style rel="stylesheet/scss" lang="scss">
@import 'src/styles/mixin.scss';
$border-color:#dcdfe6;
$left-offset:96px;
@mixin leftChange {
  padding-left:$left-offset;
  padding-top: 30px;
  box-sizing:content-box;
  @media screen and (max-width: 1205px){
    padding-left:0;
    box-sizing:border-box;
  }
}
.createPost-main-container{
  .readonlyInput{
    .el-input__inner{
      border:none;
      &:focus{
        border:none;
      }
    }
  }
  .el-time-panel.el-popper{
    box-sizing:content-box;
  }
  .el-radio__input.is-checked+.el-radio__label{
    color:#606266;
  }
  .el-upload{
    width:20%;
    margin-right:20px;
    min-width: 120px;
    .el-button--primary{
      width:100%;
    }
  }
  .videoBox,
  .leftPaddingChange{
    @include leftChange;
  }
  

}
.clearfix{
  float: left;
}
.el-form-item.is-success{
  .el-input__inner,
  .el-input__inner:focus,
  .el-textarea__inner,
  .el-textarea__inner:focus{
    border-color:$border-color;
  }
} 
.videoInfoCotainer{
  .el-card{
    border:none;
  }
  .el-card__body{
    padding:0
  }
}
</style>
